import { request } from "@tarojs/taro";
import { REQUEST_TIMEOUT, SUCCESS_CODE, REFRESH_TOKEN_CODE } from "@/constants";
import {
    getRequestUrl,
    getRequestHeaders,
    handleExpireToken,
    showErrorMsg,
} from "./helpers";

async function axios<T>(
    config: Service.RequestParam
): Promise<Service.RequestResult<T>> {
    const { method, url, data } = config;
    const axiosConfig = config.axiosConfig as Service.AxiosConfig;
    const header = getRequestHeaders(axiosConfig);
    return await new Promise((resolve, reject) => {
        request({
            /** 兼容Url不同的情况，可以通过填写完整路径 */
            url: getRequestUrl(url),
            method,
            /** 对所有请求添加时间戳以防止缓存 */
            data: { _t: Date.now(), ...data },
            header,
            timeout: REQUEST_TIMEOUT,
            success: (res) => {
                // http 状态码
                const statusCode = res.statusCode;
                const { status, message, data } =
                    res.data as Service.BackendResultConfig<T>;

                /* 成功请求 */
                if (statusCode === SUCCESS_CODE) {
                    if (status === 1 || status === 0) {
                        // 显示接口成功信息
                        if (axiosConfig.successToastMsg) {
                            showErrorMsg(message);
                        } else if (status === 1) {
                            showErrorMsg(message);
                        }
                        return resolve({
                            // error: undefined,
                            success: data,
                        });
                    }
                }
                // 显示报错信息
                showErrorMsg(message);
                // if (REFRESH_TOKEN_CODE.includes(status)) {
                //   handleExpireToken();
                // }
                return resolve({
                    error: {
                        message,
                        errorCode: status,
                    },
                    // success: undefined
                });
            },
            fail: (err) => {
                reject(err);
            },
            complete: () => {
                //
            },
        });
    });
}

export default axios;
